package com.aididi.utils;

import com.aididi.security.SysUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Auther: zx.xu
 * @Description:  获取当前登录用户
 */
public class UserContextHolder {

    /**
     * 从security线程安全上下文中获取当前登录用户名
     * @return
     */
    public static String getCurrentUserName(){
        Object principal = getOauth2Authentication().getPrincipal();
        if (principal instanceof SysUserDetails) {
            return ((SysUserDetails) principal).getUsername();
        }
        return (String) getOauth2Authentication().getPrincipal();
    }

    private static Authentication getOauth2Authentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return  authentication;
    }


}
